<template>
  <a-upload
    v-model:file-list="list"
    class="avatar-uploader"
    :max-count="9"
    action="http://192.168.0.42:5001/admin/email/uploadPicture?directoryName=test"
    :before-upload="beforeUpload"
    @change="handleChange"
    @preview="handlePreview"
    :remove="remove"
  >
  </a-upload>
  <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<script>
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { computed, reactive, toRefs, ref, createVNode } from 'vue'
import { uploadPicture } from '@/api/email/index.js'
import { message, Modal } from 'ant-design-vue'
import { useModal } from "@/hooks"

export default {
  setup(props, { emit }) {
    // // 计算属性监听的没有了响应式…… 可能是数组吧
    // const imageList1 = computed(() => {
    // 	console.log(props.fileList, "计算属性监听到的值是");
    // 	return props.fileList;
    // });
    // console.log(imageList.value, "计算属性中的imageList---");
    // console.log(imageList1, "imageList1----");
    // const imageList = ref(imageList1.value); //这样才能变成响应式的
    // console.log(imageList, "imageList----");
    const data = reactive({
      uploadLoading: false, //上传状态
      imageList: [] //图片列表
    })
    const list = computed({
      get: () => props.visible,
      set: val => {
        emit('update:visible', val)
      }
    })
    const upload = async option => {
      const { file, onSuccess } = option //option参数
      console.log(file, '上传图片---')
      let formData = new FormData()
      formData.append('file', file) //file.file
      console.log('formData1111111111111', formData)
      let res = await uploadPicture(formData, props.fileName)

      if (res.success) {
        // onSuccess(res.object)
        list.push({
          uid: file.uid,
          url: res.object,
          status: 'done',
          name: file.name
        })
        data.imageList = props.fileList.filter(el => el.status == 'done')

        console.log(data.imageList, 'data.imageList----')

        emit('change', data.imageList)
      } else {
        // 上传失败删除当前文件
        let index = data.imageList.findIndex(el => el.uid == file.uid)
        data.imageList.splice(index, 1)

        console.log(data.imageList, props.fileList, '上传失败的文件列表是')
        emit('change', data.imageList)
        message.error('上传失败啦')
      }
    }
    const beforeUpload = file => {
      console.log('上传logo图片----')
      const isJpgOrPng =
        file.type === 'image/psd' ||
        file.type === 'image/bmp' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/jpeg'

      if (!isJpgOrPng) {
        message.error('图片格式不正确!')
      }
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isLt2M) {
        message.error('图片大小不超过5MB!')
      }
      return isJpgOrPng && isLt2M
    }
    const handleChange = info => {
      if (info.file.status === 'uploading') {
        data.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        data.uploadLoading = false
        // Get this url from response in real world.
        // getBase64(info.file.originFileObj, (base64Url) => {
        // 	//   data.imageUrl = base64Url;
        // 	data.uploadLoading = false;
        // });
      }

      if (info.file.status === 'error') {
        data.uploadLoading = false
        message.error('上传错误')
      }
    }
    const previewVisible = ref(false)
    const previewImage = ref('')
    const previewTitle = ref('')
    const handleCancel = () => {
      previewVisible.value = false
      previewTitle.value = ''
    }
    // 转base64
    function getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)

        reader.onload = () => resolve(reader.result)

        reader.onerror = error => reject(error)
      })
    }

    // 预览
    const handlePreview = async file => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      previewImage.value = file.url || file.preview
      previewVisible.value = true
      previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
    }

    // 删除的时候是要将源文件删除吗还是
    const remove = async file => {
      console.log('点击了删除-----', file, file.uid)
      console.log(8888, data.imageList)
      let flag = await handleRemove(file.uid)
      return flag
    }
    const handleRemove = id => {
      return new Promise((resolve, reject) => {
        const {closeModal} = useModal.confirm({
          title: '确定删除当前文件吗?',
          icon: createVNode(ExclamationCircleOutlined),
          content: '删除后将不可恢复，请谨慎操作',
          onOk() {
            /* 
							删除图片操作
							*/
            let index = data.imageList.findIndex(el => el.uid == id)
            data.imageList.splice(index, 1)

            emit('change', data.imageList)
            console.log('删除之后', data.imageList)
            closeModal()
            resolve(true)
          },
          onCancel() {
            message.info('取消删除')
            closeModal()
            resolve(false)
          }
        })
      })
    }
    return {
      upload,
      beforeUpload,
      handleChange,
      previewVisible,
      previewImage,
      handleCancel,
      handlePreview,
      previewTitle,
      ...toRefs(data),
      remove,
      list
    }
  },

  components: {
    PlusOutlined,
    ExclamationCircleOutlined
  },

  props: {
    // 上传图片最大数量
    maxCount: {
      type: Number,
      default: 9
    },
    // 上传到阿里云的文件名
    fileName: {
      type: String,
      default: 'test'
    },
    // 图片列表-数组
    fileList: {
      type: Array,
      default: () => []
    }
  }
}
</script>
